import sys
import os
import re
import ConfigParser
import globalvar
from optparse import OptionParser
import struct
import stat
import binascii
import base64
import datetime
import pprint

def unsigned(n):
    return n & 0xFFFFFFFF

def scomo_gen(infile,name,version,vendor,outfile):


    size = os.stat(infile)[stat.ST_SIZE];        

    inf = open(infile,'rb')
    alldata = inf.read(size)
    inf.close()
    
    #write the version
    outf=open(outfile,'wb')    
    outf.write(struct.pack('I', size))
    for item in [name,version,vendor]:
        outf.write(item)
        append = 128-len(item);                
        outf.write('\x00'*append)       
        
    crcsize=binascii.crc32(alldata)    
    crcsize= unsigned(crcsize)
    outf.write(struct.pack('I',crcsize))
    outf.write(alldata)
    outf.close()
    
    if globalvar.dmlogging:
        globalvar.dmlogging.debug('scomo_gen(infile=%s,name=%s,version=%s,vendor=%s,outfile=%s)'%(infile,name,version,vendor,outfile))    
    return 0
    

def main(*argv):
    """Generate the scomo package with the apk files """
    if argv:
        argv = list(argv)
    else:
        argv = sys.argv[1:]
        
    usage = "usage: python scomo_gen.py -i [infile] -n [name] -r [version] -v [vendor] "    
    parser = OptionParser(usage=usage)    
    
    parser.add_option("-i", "--infile", dest="infile",type="string",help="input apk file  ")
    parser.add_option("-n", "--name", dest="name",type="string",help="the software name ")
    parser.add_option("-r", "--version", dest="version",type="string",help="the software version ")
    parser.add_option("-v", "--vendor", dest="vendor",type="string",help="the vendor name  ")
    parser.add_option("-o", "--outfile", dest="outfile",type="string",help="output pkg file")
    (options, args) = parser.parse_args(args=argv)
    
    if options.infile:
        infile = os.path.abspath(options.infile)
    if options.outfile:
        outfile = os.path.abspath(options.outfile)
    
    ret = scomo_gen(infile,options.name,options.version,options.vendor,outfile)
       
    print ret
        
if __name__ == "__main__":
    main()
    